import axios from 'axios'
import { Toast } from 'vant'

const service = axios.create({
  timeout: 5000
})

// Request interceptors
service.interceptors.request.use(
  config => {
    return config
  },
  error => {
    Promise.reject(error)
  }
)

// Response interceptors
service.interceptors.response.use(
  response => {
    if (response) {
      const { status, data } = response
      if (status == 200 && data) return data
      return Promise.reject(response)
    } else {
      return Promise.reject(response)
    }
  },
  error => {
    switch (error.response.status) {
      case 400:
        Toast('错误的请求')
        return Promise.reject(error)
        break
      case 401:
        Toast('服务器错误')
        location.reload()
        return Promise.reject(error)
        break
      case 405:
        Toast('当前操作不被允许')
        return Promise.reject(error)
      case 404:
        Toast('服务器错误')
        return Promise.reject(error)
      case 409:
        Toast('请求过多，先休息一下吧')
        return Promise.reject(error)
      case 500:
        Toast('服务器打瞌睡了')
        return Promise.reject(error)
      default:
        Toast(error.message)
        return Promise.reject(error)
    }
  }
)

export default service
